<?php

namespace app\v4\controller;

use app\service\AliSmsService;
use app\service\EmailService;
use app\service\JwtService;
use think\Db;
use think\facade\Cache;

class Login
{
    /**
     * 用户登录
     * 支持手机号/邮箱 + 密码登录
     * 支持手机号 + 验证码登录.
     */
    public function login()
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => [],
        ];

        $loginType = input('login_type', 'password'); // password或code
        $account = input('phone', ''); // 手机号或邮箱

        if (empty($account)) {
            $result['code'] = 1;
            $result['msg'] = '账号不能为空';

            return json($result);
        }

        // 判断是手机号还是邮箱
        $isEmail = filter_var($account, FILTER_VALIDATE_EMAIL) ? true : false;
        $field = $isEmail ? 'email' : 'phone';

        // 查询用户
        $user = Db::name('member')->where([$field => $account])->find();
        if (!$user) {
            $result['code'] = 1;
            $result['msg'] = '用户不存在，请先注册';

            return json($result);
        }

        // 密码登录
        if ($loginType === 'password') {
            $password = input('password', '');
            if (empty($password)) {
                $result['code'] = 1;
                $result['msg'] = '密码不能为空';

                return json($result);
            }

            // 验证密码
            if (!password_verify($password, $user['password'])) {
                $result['code'] = 1;
                $result['msg'] = '密码错误';

                return json($result);
            }
        }
        // 验证码登录
        elseif ($loginType === 'code') {
            $code = input('code', '');
            if (empty($code)) {
                $result['code'] = 1;
                $result['msg'] = '验证码不能为空';

                return json($result);
            }

            // 验证验证码
            $cachedCode = Cache::get($account);
            if (!$cachedCode || $cachedCode != $code) {
                $result['code'] = 1;
                $result['msg'] = '验证码错误或已过期';

                return json($result);
            }

            // 验证成功后删除缓存的验证码
            Cache::rm($account);
        } else {
            $result['code'] = 1;
            $result['msg'] = '不支持的登录方式';

            return json($result);
        }

        // 生成JWT令牌
        $payload = [
            'id' => $user['id'],
            'phone' => $user['phone'],
            'email' => $user['email'],
        ];
        $token = JwtService::createToken($payload, config('app.jwt_expire'));

        // 返回用户信息和令牌
        unset($user['password']); // 移除密码字段
        $user['nickname'] = $user['phone'] ?? $user['email'];
        $result['data'] = [
            'user' => $user,
            'token' => $token,
        ];
        $result['msg'] = '登录成功';

        return json($result);
    }

    /**
     * 用户注册
     * 支持手机号/邮箱注册.
     */
    public function register()
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => [],
        ];

        $account = input('account', ''); // 手机号或邮箱
        $code = input('code', '');
        $password = input('password', '');

        if (empty($account)) {
            $result['code'] = 1;
            $result['msg'] = '账号不能为空';

            return json($result);
        }

        if (empty($code)) {
            $result['code'] = 1;
            $result['msg'] = '验证码不能为空';

            return json($result);
        }

        if (empty($password)) {
            $result['code'] = 1;
            $result['msg'] = '密码不能为空';

            return json($result);
        }

        // 判断是手机号还是邮箱
        $isEmail = filter_var($account, FILTER_VALIDATE_EMAIL) ? true : false;
        $field = $isEmail ? 'email' : 'phone';

        // 验证验证码
        $cachedCode = Cache::get($account);
        if (!$cachedCode || $cachedCode != $code) {
            $result['code'] = 1;
            $result['msg'] = '验证码错误或已过期';

            return json($result);
        }

        // 检查用户是否已存在
        $exists = Db::name('member')->where([$field => $account])->find();
        if ($exists) {
            $result['code'] = 1;
            $result['msg'] = '该账号已注册';

            return json($result);
        }

        // 准备用户数据
        $userData = [
            'agent_id' => 0,
            'phone' => $isEmail ? '' : $account,
            'email' => $isEmail ? $account : '',
            'openid' => '',
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'create_time' => time(),
            'sex' => 0,
            'birth' => '',
            'once_nums' => 0,
            'month_day' => 0,
            'works_once_nums' => 0,
            'works_month_nums' => 0,
            'emotion_once_nums' => 0,
            'emotion_month_nums' => 0,
            'pr_once_nums' => 0,
            'pr_month_nums' => 0,
            'group_once_nums' => 0,
            'group_month_nums' => 0,
            'stu_once_nums' => 0,
            'stu_month_nums' => 0,
            'uid' => 0,
            'medical_once_nums' => 0,
        ];

        // 添加用户
        $userId = Db::name('member')->insertGetId($userData);
        if (!$userId) {
            $result['code'] = 1;
            $result['msg'] = '注册失败，请重试';

            return json($result);
        }

        // 删除缓存的验证码
        Cache::rm($account);

        // 生成JWT令牌
        $payload = [
            'id' => $userId,
            'phone' => $userData['phone'],
            'email' => $userData['email'],
        ];
        $token = JwtService::createToken($payload, config('app.jwt_expire'));

        // 返回用户信息和令牌
        $userData['id'] = $userId;
        unset($userData['password']); // 移除密码字段
        $result['data'] = [
            'user' => $userData,
            'token' => $token,
        ];
        $result['msg'] = '注册成功';

        return json($result);
    }

    /**
     * 用户退出登录.
     */
    public function logout()
    {
        // JWT无需在服务端处理退出登录，客户端删除token即可
        return json(['code' => 0, 'data' => [], 'msg' => '退出成功']);
    }

    /**
     * 修改密码
     */
    public function changePassword()
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => [],
        ];

        // 获取JWT令牌中的用户ID
        $token = JwtService::getTokenFromHeader();
        if (!$token) {
            $result['code'] = 401;
            $result['msg'] = '请先登录';

            return json($result);
        }

        $payload = JwtService::verifyToken($token);
        if (!$payload) {
            $result['code'] = 401;
            $result['msg'] = '登录已过期，请重新登录';

            return json($result);
        }

        $userId = $payload['id'];
        $oldPassword = input('old_password', '');
        $newPassword = input('new_password', '');

        if (empty($oldPassword) || empty($newPassword)) {
            $result['code'] = 1;
            $result['msg'] = '原密码和新密码不能为空';

            return json($result);
        }

        // 验证原密码
        $user = Db::name('member')->where(['id' => $userId])->find();
        if (!$user) {
            $result['code'] = 1;
            $result['msg'] = '用户不存在';

            return json($result);
        }

        if (!password_verify($oldPassword, $user['password'])) {
            $result['code'] = 1;
            $result['msg'] = '原密码错误';

            return json($result);
        }

        // 更新密码
        $update = Db::name('member')->where(['id' => $userId])->update([
            'password' => password_hash($newPassword, PASSWORD_DEFAULT),
        ]);

        if (!$update) {
            $result['code'] = 1;
            $result['msg'] = '密码修改失败，请重试';

            return json($result);
        }

        $result['msg'] = '密码修改成功';

        return json($result);
    }

    /**
     * 发送验证码
     * 根据邮箱还是手机, 发送不同的验证码
     */
    public function sendSmsCode()
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => [
                'res' => '',
            ],
        ];

        $phone = input('phone', '');

        if (empty($phone)) {
            $result['code'] = 1;
            $result['msg'] = '手机号或邮箱不能为空!';

            return json($result);
        }

        // 判断是手机号还是邮箱
        $isEmail = filter_var($phone, FILTER_VALIDATE_EMAIL) ? true : false;

        // 如果不是邮箱，则验证手机号格式
        if (!$isEmail && !preg_match('/^1[3-9]\d{9}$/', $phone)) {
            $result['code'] = 1;
            $result['msg'] = '手机号格式不正确!';

            return json($result);
        }

        // 生成验证码
        $code = rand(100000, 999999);

        // 发送验证码
        if ($isEmail) {
            // 使用邮箱发送验证码
            $sendResult = EmailService::sendCode($phone, $code);
            if ($sendResult !== true) {
                $result['code'] = 1;
                $result['msg'] = '邮箱验证码发送失败: '.$sendResult;

                return json($result);
            }
        } else {
            // 使用阿里云短信发送验证码
            $aliSmsConfig = config('app.ali_sms');
            $args = [
                'phone' => $phone,
                'template' => $aliSmsConfig['regCodeTpl'],
                'params' => '{"code":"'.$code.'"}',
            ];

            $sendResult = AliSmsService::main($args);
            if ($sendResult !== true) {
                $result['code'] = 1;
                $result['msg'] = '短信验证码发送失败';

                return json($result);
            }
        }

        // 缓存验证码，有效期5分钟
        Cache::set($phone, $code, 300);

        // 检测当前手机号/邮箱是否存在
        $field = $isEmail ? 'email' : 'phone';
        $userId = Db::name('member')->where([$field => $phone])->column('id');

        $result['msg'] = '验证码发送成功';
        $result['data']['is_show'] = empty($userId) ? 1 : 0;

        return json($result);
    }
}
